import { useRef } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, DatePicker, Input, Popconfirm, Table } from 'antd';
import { Dayjs } from 'dayjs';

import Filter from '@/components/filter';
import Text from '@/components/text';
import Upload from '@/components/upload';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import {
  environmentalDangerInfoDelete,
  environmentalDangerInfoPage
} from '@/services/bizApi/huanbaoweixianfeiwuguanlibiaojiekou';

import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.EnvironmentalDangerInfoEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const [filter] = Filter.useForm();

  const table = useAntdTable(
    async ({ current, pageSize }, { id, monitorTime, ...formData }) => {
      const [monitorTimeBegin, monitorTimeEnd] = ((monitorTime as [Dayjs?, Dayjs?]) || []).map(
        (v) => v?.format('YYYY-MM-DD HH:mm:ss')
      );
      const res = await environmentalDangerInfoPage({
        ...formData,
        ...id,
        monitorTimeBegin,
        monitorTimeEnd,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={() => {
                  edit.current?.open({
                    type: 'add',
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                新增
              </Button>
            )}
          </>
        }
      >
        <Filter.Item name="name">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入名称"
          />
        </Filter.Item>
        <Filter.Item name="monitorTime">
          <DatePicker.RangePicker placeholder={['监测时间', '监测时间']} />
        </Filter.Item>
        <Filter.Item name="chargeUserName">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入负责人"
          />
        </Filter.Item>
        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            width: 60,
            render: (_text, _record, index) => index + 1
          },
          {
            title: '名称',
            dataIndex: 'name'
          },
          {
            title: '内容',
            dataIndex: 'content'
          },
          {
            title: '监测时间',
            dataIndex: 'monitorTime'
          },
          {
            title: '负责人',
            dataIndex: 'chargeUserName'
          },
          {
            title: '附件',
            dataIndex: 'fileId',
            render: (url, row) => {
              if (!url || url === '-') return;
              return (
                <Upload
                  disabled
                  value={url as unknown as string}
                  // base64
                  //  accept="image/*"
                  maxCount={1}
                >
                  {/* <Button>上传附件</Button> */}
                </Upload>
              );
            }
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'edit',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      编辑
                    </Text>
                  )}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'detail',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      详情
                    </Text>
                  )}

                  {permission.check() && (
                    <Popconfirm
                      title={`确定删除吗？`}
                      onConfirm={async () => {
                        const res = await environmentalDangerInfoDelete({
                          id: row.id as unknown as string
                        });

                        store.app?.message.success(res.message);
                        table.refresh();

                        return res.success;
                      }}
                    >
                      <Text type="danger">删除</Text>
                    </Popconfirm>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
    </>
  );
};

export default Page;
